package com.uzai.console.service.exportinfo.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.uzai.common.enums.MerConfigKeyEnum;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.config.UzaiConsoleSysConfig;
import com.uzai.console.dto.exportinfo.ExportInfoIdDto;
import com.uzai.console.dto.exportinfo.ExportInfoQuery;
import com.uzai.console.entity.ExportInfo;
import com.uzai.console.entity.MerAccDetail;
import com.uzai.console.entity.MerBaseConfig;
import com.uzai.console.entity.Merchant;
import com.uzai.console.enums.ExportInfoTypeEnum;
import com.uzai.console.enums.MerAccDetailSourceSubtypeEnum;
import com.uzai.console.enums.MerAccDetailSourceTypeEnum;
import com.uzai.console.mapper.ExportInfoMapper;
import com.uzai.console.mapper.MerAccDetailMapper;
import com.uzai.console.mapper.MerBaseConfigMapper;
import com.uzai.console.mapper.MerchantMapper;
import com.uzai.console.service.exportinfo.ExportInfoService;
import com.uzai.console.service.qiniu.QiniuService;
import com.uzai.console.service.tencent.TencentCosService;
import com.uzai.console.vo.exportinfo.ExportAmountVo;
import com.uzai.console.vo.exportinfo.ExportInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/***
 * @author liuqi
 * @date 2021年08月25日 20:18
 */
@Service
public class ExportInfoServiceImpl implements ExportInfoService {

    Logger logger = LoggerFactory.getLogger(ExportInfoServiceImpl.class);

    @Autowired
    private ExportInfoMapper exportInfoMapper;
    @Autowired
    private MerBaseConfigMapper merBaseConfigMapper;
    @Autowired
    private QiniuService qiniuService;
    @Autowired
    private TencentCosService tencentCosService;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private MerAccDetailMapper merAccDetailMapper;
    @Autowired
    private UzaiConsoleSysConfig uzaiConsoleSysConfig;

    /**
     * 查询文件导出记录列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param exportInfoQuery
     * @return null
     */
    public Page<ExportInfoVo> findExportInfoList(ExportInfoQuery exportInfoQuery){
        //新建返回到页面的LIST对象
        List<ExportInfoVo> exportInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<ExportInfo> page = new Page<>();
        exportInfoQuery.convert(page);
        ArrayList<ExportInfo> exportInfoList =  exportInfoMapper.findByList(page, exportInfoQuery);
        if(exportInfoList != null && exportInfoList.size() > 0){
            for (ExportInfo exportInfo : exportInfoList){
                ExportInfoVo exportInfoVo = new ExportInfoVo();
                BeanUtils.copyProperties(exportInfo, exportInfoVo);
                ExportInfoTypeEnum exportInfoTypeEnum = ExportInfoTypeEnum.getById(exportInfo.getType());
                if(exportInfoTypeEnum != null){
                    exportInfoVo.setTypeName(exportInfoTypeEnum.getDesc());
                }
                exportInfoVoList.add(exportInfoVo);
            }
        }
        //返回到页面分页对象
        Page<ExportInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(exportInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查出文件下载
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param exportInfoIdDto
     * @return null
     */
    public void deleteExportInfo(ExportInfoIdDto exportInfoIdDto){
        if(exportInfoIdDto.getId() == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择文件");
        }
        exportInfoMapper.deleteById(exportInfoIdDto.getId(), exportInfoIdDto.getMerId());
    }

    /**
     * 上传文件
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param type 文件类型
     * @return null
     */
    @Transactional
    public void uploadExportFile(InputStream inputStream, Long merId, String fileName, ExportAmountVo exportAmountVo, Integer type){

        ExportInfoTypeEnum exportInfoTypeEnum = ExportInfoTypeEnum.getById(type);

        //获取系统默认账号配置的上传文件存储类型
        Long defaultMerId = uzaiConsoleSysConfig.getDefaultMerId();
        MerBaseConfig merBaseConfig_fileSaveType = merBaseConfigMapper.selectByMerId(defaultMerId, MerConfigKeyEnum.FILE_SAVE_TYPE.getValue());
        if(merBaseConfig_fileSaveType == null || StringUtils.isBlank(merBaseConfig_fileSaveType.getVal())) { //还未配置，请先配置存储空间
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置云存储方式");
        }
        String fileUrl;
        Integer fileSaveType = Integer.valueOf(merBaseConfig_fileSaveType.getVal());
        if(fileSaveType.intValue() == 1){ //使用默认账号的七牛云
            fileUrl =  qiniuService.upload(defaultMerId, inputStream, fileName);     //上传
        }else if(fileSaveType.intValue() == 2){ //使用默认账号的腾讯云
            fileUrl =  tencentCosService.upload(defaultMerId, inputStream, fileName); //上传图片
        }else{
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请先设置默认的上传云存储类型");
        }

        try {
            inputStream.close();
        }catch (Exception e){
            logger.error("----关闭上传云服务器流失败--error={}", e.getMessage());
        }finally {

        }

        int now = DateUtil.getNowTime();

        //文件上传成功，插入到导出文件数据库当中
        if(StringUtils.isNotBlank(fileUrl)){

            //保存账户余额
            //处理余额支付信息
            //查询账号信息
            Merchant merchant = merchantMapper.selectById(merId);
            if(merchant == null) {
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该运营商不存在");
            }

            //判断余额大小
            Double balance = merchant.getBalance();
            if(balance.doubleValue() < exportAmountVo.getAmountTotal()){ //不够支付
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账户余额不足");
            }

            //修改账户余额
            merchant.setBalance(balance - exportAmountVo.getAmountTotal());
            merchant.setUpdateTime(now);
            int j = merchantMapper.updateBalance(merchant);

            if(j <= 0){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "网络异常");
            }

            //添加账户明细
            String trandeNo = Tools.getCurrentTimeByFormat("yyyyMMdd") + IdWorker.getIdStr();

            MerAccDetail merAccDetail = new MerAccDetail();
            merAccDetail.setId(IdWorker.getId());
            merAccDetail.setMerId(merchant.getId());
            merAccDetail.setOperateType(2);//支出
            merAccDetail.setMoney(merchant.getBalance());
            merAccDetail.setCgMoney(exportAmountVo.getAmountTotal());
            merAccDetail.setSourceType(MerAccDetailSourceTypeEnum.EXPORT_INFO.getId());
            merAccDetail.setSubtype(exportInfoTypeEnum.getKey());
            merAccDetail.setTradeno(trandeNo);
            merAccDetail.setCreateTime(now);
            merAccDetail.setUpdateTime(now);
            merAccDetailMapper.insert(merAccDetail);

            //插入导出文件表
            ExportInfo exportInfo = new ExportInfo();
            exportInfo.setId(IdWorker.getId());
            exportInfo.setMerId(merId);
            exportInfo.setFileName(fileName);
            exportInfo.setFileUrl(fileUrl);
            exportInfo.setType(exportInfoTypeEnum.getId());
            exportInfo.setDataCount(Tools.getLong(exportAmountVo.getCountTotal()).intValue());
            exportInfo.setAmount(Tools.getDouble(exportAmountVo.getAmountTotal()));
            exportInfo.setPrice(Tools.getDouble(exportAmountVo.getPrice()));
            exportInfo.setStoreType(fileSaveType);
            exportInfo.setCreateTime(now);
            exportInfo.setUpdateTime(now);
            exportInfoMapper.insert(exportInfo);

        }

    }


}
